package com.ross.springboot.service.impl;

import com.ross.springboot.entity.RoleResources;
import com.ross.springboot.mapper.UserRoleMapper;
import com.ross.springboot.service.IRoleResourcesService;
import com.ross.springboot.shiro.MyShiroRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ross
 * @since 2020-07-24
 */
@Service
public class RoleResourcesServiceImpl extends BaseService<RoleResources> implements IRoleResourcesService {

    @Resource
    private UserRoleMapper userRoleMapper;
    /*@Autowired
    private MyShiroRealm myShiroRealm;*/

    @Autowired
    private MyShiroRealm myShiroRealm;

    @Override
    //更新权限
    @Transactional(propagation= Propagation.REQUIRED,readOnly=false,rollbackFor={Exception.class})
    public void addRoleResources(RoleResources roleResources) {
        //删除
        Example example = new Example(RoleResources.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("rolrid",roleResources.getRoleId());
        mapper.deleteByExample(example);

        //添加
        if (!StringUtils.isEmpty(roleResources.getResourcesId())){
            String[] resourcesArr = roleResources.getResourcesId().split(",");
            for (String resourcesId : resourcesArr){
                RoleResources r = new RoleResources();
                r.setRoleId(roleResources.getRoleId());
                r.setResourcesId(roleResources.getResourcesId());
                mapper.insert(r);
            }
        }

        List<Integer> userIds = this.userRoleMapper.findUserIdByRoleId(roleResources.getRoleId());
        //更新当前登录的用户的权限缓存
        myShiroRealm.clearUserAuthByUserId(userIds);

    }
}
